using DesktopWidgetApp.Shared;
using DesktopWidgetApp.UI.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

namespace DesktopWidgetApp.UI.Views
{
    /// <summary>
    /// TaskManagerWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TaskManagerWindow : Window, INotifyPropertyChanged
    {
        private readonly AppService _appService;
        private List<TaskItemViewModel> _allTasks;
        private string _currentUserId = "user-1";
        private TaskStatus _currentFilterStatus = TaskStatus.All;
        private Priority _currentFilterPriority = Priority.All;
        private string _currentSearchText = string.Empty;

        /// <summary>
        /// 构造函数
        /// </summary>
        public TaskManagerWindow()
        {
            InitializeComponent();
            _appService = AppService.Instance;
            _allTasks = new List<TaskItemViewModel>();
        }

        /// <summary>
        /// 窗口加载事件
        /// </summary>
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            await LoadTasksAsync();
        }

        /// <summary>
        /// 加载任务列表
        /// </summary>
        private async System.Threading.Tasks.Task LoadTasksAsync()
        {
            try
            {
                var tasks = await _appService.TaskService.GetAllTasksAsync(_currentUserId);
                _allTasks = tasks.Select(MapTaskToViewModel).ToList();
                ApplyFilters();
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载任务失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 将TaskItem映射到TaskItemViewModel
        /// </summary>
        private TaskItemViewModel MapTaskToViewModel(TaskItem taskItem)
        {
            return new TaskItemViewModel
            {
                Id = taskItem.Id,
                Title = taskItem.Title,
                Description = taskItem.Description,
                Status = taskItem.Status,
                Priority = taskItem.Priority,
                DueDate = taskItem.DueDate,
                Tags = taskItem.Tags ?? new List<string>(),
                IsCompleted = taskItem.Status == TaskStatus.Completed,
                IsDueDatePassed = taskItem.DueDate.HasValue && taskItem.DueDate.Value < DateTime.Now && taskItem.Status != TaskStatus.Completed
            };
        }

        /// <summary>
        /// 应用筛选器
        /// </summary>
        private void ApplyFilters()
        {
            var filteredTasks = _allTasks.AsEnumerable();

            // 应用状态筛选
            if (_currentFilterStatus != TaskStatus.All)
            {
                filteredTasks = filteredTasks.Where(t => t.Status == _currentFilterStatus);
            }

            // 应用优先级筛选
            if (_currentFilterPriority != Priority.All)
            {
                filteredTasks = filteredTasks.Where(t => t.Priority == _currentFilterPriority);
            }

            // 应用搜索文本
            if (!string.IsNullOrEmpty(_currentSearchText))
            {
                var searchText = _currentSearchText.ToLower();
                filteredTasks = filteredTasks.Where(t => 
                    t.Title.ToLower().Contains(searchText) || 
                    (t.Description != null && t.Description.ToLower().Contains(searchText)) ||
                    (t.Tags != null && t.Tags.Any(tag => tag.ToLower().Contains(searchText)))
                );
            }

            TaskListDataGrid.ItemsSource = filteredTasks.ToList();
        }

        /// <summary>
        /// 任务筛选器选择变化事件
        /// </summary>
        private void TaskFilterComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (TaskFilterComboBox.SelectedIndex == 0) _currentFilterStatus = TaskStatus.All;
            else if (TaskFilterComboBox.SelectedIndex == 1) _currentFilterStatus = TaskStatus.Todo;
            else if (TaskFilterComboBox.SelectedIndex == 2) _currentFilterStatus = TaskStatus.InProgress;
            else if (TaskFilterComboBox.SelectedIndex == 3) _currentFilterStatus = TaskStatus.Completed;
            else if (TaskFilterComboBox.SelectedIndex == 4) _currentFilterStatus = TaskStatus.Paused;
            else if (TaskFilterComboBox.SelectedIndex == 5) _currentFilterStatus = TaskStatus.Cancelled;

            ApplyFilters();
        }

        /// <summary>
        /// 优先级筛选器选择变化事件
        /// </summary>
        private void PriorityFilterComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PriorityFilterComboBox.SelectedIndex == 0) _currentFilterPriority = Priority.All;
            else if (PriorityFilterComboBox.SelectedIndex == 1) _currentFilterPriority = Priority.Low;
            else if (PriorityFilterComboBox.SelectedIndex == 2) _currentFilterPriority = Priority.Medium;
            else if (PriorityFilterComboBox.SelectedIndex == 3) _currentFilterPriority = Priority.High;
            else if (PriorityFilterComboBox.SelectedIndex == 4) _currentFilterPriority = Priority.Urgent;

            ApplyFilters();
        }

        /// <summary>
        /// 搜索文本变化事件
        /// </summary>
        private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _currentSearchText = SearchTextBox.Text;
            ApplyFilters();
        }

        /// <summary>
        /// 添加任务按钮点击事件
        /// </summary>
        private async void AddTaskButton_Click(object sender, RoutedEventArgs e)
        {
            var taskEditWindow = new TaskEditWindow();
            if (taskEditWindow.ShowDialog() == true)
            {
                try
                {
                    var newTask = new TaskItem
                    {
                        Title = taskEditWindow.TaskTitle,
                        Description = taskEditWindow.TaskDescription,
                        Status = TaskStatus.Todo,
                        Priority = taskEditWindow.TaskPriority,
                        DueDate = taskEditWindow.TaskDueDate,
                        Tags = taskEditWindow.TaskTags?.Split(',').Select(t => t.Trim()).Where(t => !string.IsNullOrEmpty(t)).ToList(),
                        CreatedById = _currentUserId,
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now
                    };

                    await _appService.TaskService.CreateTaskAsync(newTask);
                    await LoadTasksAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("创建任务失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 编辑任务按钮点击事件
        /// </summary>
        private async void EditTaskButton_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button == null) return;

            var taskId = (Guid)button.Tag;
            var task = await _appService.TaskService.GetTaskByIdAsync(taskId, _currentUserId);
            if (task == null) return;

            var taskEditWindow = new TaskEditWindow
            {
                TaskTitle = task.Title,
                TaskDescription = task.Description,
                TaskStatus = task.Status,
                TaskPriority = task.Priority,
                TaskDueDate = task.DueDate,
                TaskTags = task.Tags != null ? string.Join(", ", task.Tags) : string.Empty
            };

            if (taskEditWindow.ShowDialog() == true)
            {
                try
                {
                    task.Title = taskEditWindow.TaskTitle;
                    task.Description = taskEditWindow.TaskDescription;
                    task.Status = taskEditWindow.TaskStatus;
                    task.Priority = taskEditWindow.TaskPriority;
                    task.DueDate = taskEditWindow.TaskDueDate;
                    task.Tags = taskEditWindow.TaskTags?.Split(',').Select(t => t.Trim()).Where(t => !string.IsNullOrEmpty(t)).ToList();
                    task.UpdatedAt = DateTime.Now;

                    await _appService.TaskService.UpdateTaskAsync(task);
                    await LoadTasksAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("更新任务失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 删除任务按钮点击事件
        /// </summary>
        private async void DeleteTaskButton_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button == null) return;

            var taskId = (Guid)button.Tag;
            var result = MessageBox.Show("确定要删除这个任务吗？", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    await _appService.TaskService.DeleteTaskAsync(taskId, _currentUserId);
                    await LoadTasksAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("删除任务失败: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        #region INotifyPropertyChanged Implementation
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }

    /// <summary>
    /// 任务项视图模型
    /// </summary>
    public class TaskItemViewModel
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public TaskStatus Status { get; set; }
        public Priority Priority { get; set; }
        public DateTime? DueDate { get; set; }
        public List<string> Tags { get; set; }
        public bool IsCompleted { get; set; }
        public bool IsDueDatePassed { get; set; }

        // 为显示标签创建一个字符串属性
        public string TagsString => Tags != null ? string.Join(", ", Tags) : string.Empty;
    }

    /// <summary>
    /// 扩展TaskStatus枚举，添加All选项
    /// </summary>
    public enum TaskStatus
    {
        All = -1,
        Todo = 0,
        InProgress = 1,
        Completed = 2,
        Paused = 3,
        Cancelled = 4
    }

    /// <summary>
    /// 扩展Priority枚举，添加All选项
    /// </summary>
    public enum Priority
    {
        All = -1,
        Low = 0,
        Medium = 1,
        High = 2,
        Urgent = 3
    }
}